<?php

namespace app\admin\controller;

use think\Lang;
use think\Session;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Order extends AdminControl
{

    const EXPORT_SIZE = 1000;

    public function _initialize()
    {
        parent::_initialize();
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/vrorder.lang.php');
    }

    public function index()
    {
        $order_model = model('order');
        $condition = array();

        $order_sn = input('param.order_sn');
        if ($order_sn) {
            $condition['ds_app_order.order_sn'] = $order_sn;
        }
        $is_cancel = input('param.is_cancel');
        if ($is_cancel) {
            $condition['ds_app_order.is_cancel'] = $is_cancel;
        }
        $order_type = input('param.order_type');
        if ($order_type) {
            $condition['ds_app_order.app_order_type'] = $order_type;
        }

        $order_state = input('param.order_state');

        if (in_array($order_state, array('0', '1', '2', '3', '4'))) {
            $condition['ds_app_order.order_status'] = $order_state;
        }

        $buyer_name = input('param.buyer_name');
        if ($buyer_name) {
            $condition['ds_app_order.member_name'] = $buyer_name;
        }
        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['ds_app_order.create_time'] = array('between', array($start_unixtime, $end_unixtime));
        }
//        $condition['ds_app_order.is_cancel'] = 0;
        if (isset($condition['ds_app_order.order_status']) && $condition['ds_app_order.order_status'] == 4) {
            $condition['ds_app_order.order_status'] = 1;
            $condition['ds_app_order.refund_price'] = 1;
        }
        $order_list = $order_model->getapp_OrderList($condition, 10);

        #判断项目定制的订单状态
        foreach ($order_list as $key => $value) {
            if ($value['app_order_type'] == 2) {
                // $project_order_info = db('orderproject')->where(['order_id'=>$value['app_order_project_id']])->find();
                $project_order_info = db('order')->alias('o')
                    ->join('orderproject op', 'o.orderproject_id=op.order_id')
                    ->field('op.*,o.order_state as zhu_order_state,o.orderproject_id')
                    ->where(['o.order_id' => $value['order_ids']])->find();
                $order_list[$key]['project_order_status'] = $project_order_info['order_state'];
                $order_list[$key]['zhu_order_state'] = $project_order_info['zhu_order_state'];
                $order_list[$key]['order_sn'] = $project_order_info['order_sn'];
            } elseif ($value['app_order_type'] == 3) {
                $service_info = db('s_order')->where(['order_id' => $value['app_order_service_id']])->find();
                $order_list[$key]['order_sn'] = $service_info['order_sn'];
            }
        }


        #大订单退款
        foreach ($order_list as $k => $v) {
            if ($v['order_status'] == 1 && $v['refund_price'] == 1) {
                $order_list[$k]['order_status'] = '4';
            }
        }
        $this->assign('show_page', $order_model->page_info->render());

        $this->assign('order_list', $order_list);
        $this->assign('order_status', ['0' => '待付款', '1' => '代收货', '2' => '已完成', '3' => '已取消', '4' => '待退款']);
        $this->assign('app_order_type', ['1' => '销售订单', '2' => '项目定制订单', '3' => '服务配件订单']);

        $this->assign('project_order_status', ['0' => '待付款', '10' => '未付款', '20' => '已付款', '30' => '已发货', '40' => '已收货', '50' => '已取消']);

        $this->assign('service_order_status', ['0' => '待付款', '1' => '进行中', '2' => '已完成', '30' => '已发货', '40' => '已收货', '50' => '已取消']);

        $this->assign('filtered', $condition ? 1 : 0); //是否有查询条件
        $this->setAdminCurItem('index');

        return $this->fetch('index');
    }


    /**
     * 待审核发票管理
     * */
    public function invoice_list()
    {
        $order_model = model('order');
        $condition = array();

        $order_sn = input('param.order_sn');
        if ($order_sn) {
            $condition['order_sn'] = $order_sn;
        }

        $condition['ds_app_order.invoice_status'] = 2;

        $order_state = input('param.order_state');
        if (in_array($order_state, array('0', '1', '2', '3', '4'))) {
            $condition['order_status'] = $order_state;
        }

        $buyer_name = input('param.buyer_name');
        if ($buyer_name) {
            $condition['member_name'] = $buyer_name;
        }
        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['create_time'] = array('between', array($start_unixtime, $end_unixtime));
        }
        $condition['is_cancel'] = 0;

        if (isset($condition['order_status']) && $condition['order_status'] == 4) {
            $condition['order_status'] = 1;
            $condition['refund_price'] = 1;

            $order_list = $order_model->getapp_OrderList($condition, 10);
        } else {
            $order_list = $order_model->getapp_OrderList($condition, 10);
        }


        foreach ($order_list as $k => $v) {
            if ($v['order_status'] == 1 && $v['refund_price'] == 1) {
                $order_list[$k]['order_status'] = '4';
            }
        }
        $this->assign('show_page', $order_model->page_info->render());

        $this->assign('order_list', $order_list);
        $this->assign('order_status', ['0' => '待付款', '1' => '代收货', '2' => '已完成', '3' => '已取消', '4' => '待退款']);

        $this->assign('filtered', $condition ? 1 : 0); //是否有查询条件
        $this->setAdminCurItem('invoice_list');

        return $this->fetch('invoice_list');
    }


    /*
      大订单获取小订单列表
     */
    public function order_list()
    {
        $order_id = intval(input('param.order_id'));
        // echo $order_id;die;
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }
        $app_order_info = db('app_order')->where('app_order_id', $order_id)->find();
        // p($app_order_info);die;
        if (empty($app_order_info)) {
            $this->error('操作失败');
        }
        if ($app_order_info['invoice_status'] != '0') {
//            $invoice_info = db('invoice')->where('app_order_id', $order_id)->find();
            $tblname = 'invoice';
            $field = 'a.*,b.name,b.type,b.billing_type';
            $where['a.app_order_id'] = $order_id;
            $where['b.status'] = 1;
            $where['b.is_del'] = 0;
            $invoice_info = db($tblname . ' a')->join('__INVOICE_TYPE__ b', 'a.invoice_type_id=b.id')->where($where)->field($field)->find();
            $this->assign('invoice_info', $invoice_info);
            $this->assign('app_order_info', $app_order_info);
        }

        $order_list = db('order')->where('order_id', 'in', $app_order_info['order_ids'])->select();
        // p($app_order_info);die;
        if (empty($order_list)) {
            $this->error('操作失败');
        }

        #判断项目定制的订单状态
        foreach ($order_list as $key => $value) {
            if ($value['orderproject_id'] > 0) {
                // $project_order_info = db('orderproject')->where(['order_id'=>$value['orderproject_id']])->find();
                $project_order_info = db('order')->alias('o')
                    ->join('orderproject op', 'o.orderproject_id=op.order_id')
                    ->field('op.*,o.order_state as zhu_order_state,o.orderproject_id')
                    ->where(['o.order_id' => $value['order_id']])->find();
                $order_list[$key]['project_order_status'] = $project_order_info['order_state'];
                $order_list[$key]['zhu_order_state'] = $project_order_info['zhu_order_state'];
            }
        }

        #大订单退款
        foreach ($order_list as $k => $v) {
            if ($v['order_state'] == 20 && $v['refund_state'] == 1) {
                $order_list[$k]['order_state'] = '50';
            }
        }


        $this->assign('order_list', $order_list);

        $this->assign('order_status', ['0' => '已取消', '10' => '未付款', '20' => '已付款', '30' => '已发货', '40' => '已收货', '50' => '待退款']);
        $this->assign('project_order_status', ['0' => '待付款', '10' => '未付款', '20' => '已付款', '30' => '已发货', '40' => '已收货', '50' => '已取消']);
        $this->assign('service_order_status', ['0' => '待付款', '10' => '未付款', '20' => '进行中', '30' => '已发货', '40' => '已收货', '50' => '已取消']);
        return $this->fetch('order_list');
    }

    /**
     * 平台订单状态操作
     *
     */
    public function change_state()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }
        $order_model = model('order');

        //获取订单详细
        $condition = array();
        $condition['order_id'] = $order_id;
        $order_info = $order_model->getOrderInfo($condition);

        $state_type = input('param.state_type');
        if ($state_type == 'cancel') {
            $result = $this->_order_cancel($order_info);
            if (!$result['code']) {
                $this->error($result['msg']);
            } else {
                ds_json_encode(10000, $result['msg']);
            }
        } elseif ($state_type == 'receive_pay') {
            $result = $this->_order_receive_pay($order_info, input('post.'));
            if (!$result['code']) {
                $this->error($result['msg']);
            } else {
                dsLayerOpenSuccess($result['msg'], 'Order/index');
            }
        }
    }


    /**
     * 平台订单删除订单 （作废）
     *
     */
    public function del_order()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $app_order_info = db('app_order')->where('app_order_id', $order_id)->where('is_cancel', '0')->find();
        // p($app_order_info);die;
        if (empty($app_order_info)) {
            ds_json_encode(10001, '操作失败');
        }
        $order_info = db('order')->where('apporder_id', $order_id)->select();
        if (empty($order_info)) {
            ds_json_encode(10001, '操作失败');
        }

        #删除 订单表
        $order_ids = explode(',', $app_order_info['order_ids']);
        foreach ($order_ids as $k => $v) {
            db('order')->where('order_id', $v)->data(['is_cancel' => '1'])->update();
        }
        $res = db('app_order')->where('app_order_id', $order_id)->data(['is_cancel' => '1', 'cancel_time' => time(), 'order_status' => 2])->update();

        if (!$res) {
            ds_json_encode(10001, '操作失败');
        } else {
            ds_json_encode(10000, '操作成功');
        }
    }

    /**
     * 平台退款大订单
     *
     */
    public function refund_order()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }

        $app_order_info = db('app_order')->where('app_order_id', $order_id)->where('is_cancel', '0')->find();
        // p($app_order_info);die;
        if (empty($app_order_info)) {
            ds_json_encode(10001, '操作失败');
        }
        $order_info = db('order')->where('apporder_id', $order_id)->select();
        if (empty($order_info)) {
            ds_json_encode(10001, '操作失败');
        }

        #更新大订单表 订单表 订单商品表
        $order_ids = explode(',', $app_order_info['order_ids']);
        $ordergoods_ids = explode(',', $app_order_info['ordergoods_ids']);
        foreach ($order_ids as $k => $v) {
            // db('order')->where('order_id', $v)->data(['refund_state' => '4','order_state' => '0'])->update();
            db('order')->where('order_id', $v)->data(['refund_state' => '3', 'order_state' => '0'])->update();

        }
        foreach ($ordergoods_ids as $k => $v) {
            db('ordergoods')->where('rec_id', $v)->data(['return_status' => '6'])->update();
        }
        $res = db('app_order')->where('app_order_id', $order_id)->data(['order_status' => '2', 'audit_refund' => 0])->update();

        //更新退款表  改为已完成
        db('refundreturn')->where(['app_order_id' => $order_id])->update(['refund_state' => 3]);

        //退款完成 返回相应积分
        /* $member_info = db('member')->where(['member_id'=>$app_order_info['user_id']])->find();
         $count = $member_info['member_points'] + $app_order_info['use_integral'];
         db('member')->where(['member_id'=>$app_order_info['user_id']])->update(['member_points'=>$count]);*/

        if (!$res) {
            ds_json_encode(10001, '操作失败');
        } else {
            ds_json_encode(10000, '操作成功');
        }
    }


    /**
     * 系统取消订单
     */
    private function _order_cancel($order_info)
    {
        $order_id = $order_info['order_id'];
        $order_model = model('order');
        $logic_order = model('order', 'logic');
        $if_allow = $order_model->getOrderOperateState('system_cancel', $order_info);
        if (!$if_allow) {
            return ds_callback(false, lang('no_right_operate'));
        }
        $result = $logic_order->changeOrderStateCancel($order_info, 'system', $this->admin_info['admin_name']);
        if ($result['code']) {
            $this->log(lang('order_log_cancel') . ',' . lang('ds_order_sn') . ':' . $order_info['order_sn'], 1);
        }
        return $result;
    }

    /**
     * 系统收到货款
     * @throws Exception
     */
    private function _order_receive_pay($order_info, $post)
    {
        $order_id = $order_info['order_id'];
        $order_model = model('order');
        $logic_order = model('order', 'logic');
        $if_allow = $order_model->getOrderOperateState('system_receive_pay', $order_info);
        if (!$if_allow) {
            return ds_callback(false, lang('no_right_operate'));
        }

        if (!request()->isPost()) {
            $this->assign('order_info', $order_info);
            //显示支付接口列表
            $payment_list = model('payment')->getPaymentOpenList();
            //去掉预存款和货到付款
            foreach ($payment_list as $key => $value) {
                if ($value['payment_code'] == 'predeposit' || $value['payment_code'] == 'offline') {
                    unset($payment_list[$key]);
                }
            }
            $this->assign('payment_list', $payment_list);
            echo $this->fetch('receive_pay');
            exit;
        } else {
            $order_list = $order_model->getOrderList(array('pay_sn' => $order_info['pay_sn'], 'order_state' => ORDER_STATE_NEW));
            $result = $logic_order->changeOrderReceivePay($order_list, 'system', $this->admin_info['admin_name'], $post);
            if ($result['code']) {
                $this->log('将订单改为已收款状态,' . lang('ds_order_sn') . ':' . $order_info['order_sn'], 1);
            }
            return $result;
        }
    }

    /**
     * Notes:申请发票审核
     * User: shen
     * Date: 2020/5/18
     * Time: 15:02
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function invoice_state()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error('操作失败');
        }
        if (!request()->isPost()) {
//            $invoice_info = db('invoice')->where('app_order_id',$order_id)->find();
            $tblname = 'invoice';
            $field = 'a.*,b.name,b.type,b.billing_type';
            $where['a.app_order_id'] = $order_id;
            $where['b.status'] = 1;
            $where['b.is_del'] = 0;
            $invoice_info = db($tblname . ' a')->join('__INVOICE_TYPE__ b', 'a.invoice_type_id=b.id')->where($where)->field($field)->find();
            //获取发票类型
            if (!empty($invoice_info['invoice_type_id'])) {
                $invoice_type_info = db('invoice_type')->where(['id' => $invoice_info['invoice_type_id']])->find();
                $this->assign('invoice_type_info', $invoice_type_info);
            }
            if (empty($invoice_info)) {
                $this->error('操作失败');
            }
            $app_order_info = db('app_order')->where('app_order_id', $order_id)->find();
            #项目定制
            if ($app_order_info['app_order_type'] == 2) {
                $project_order_info = db('orderproject')->where(['order_id' => $app_order_info['app_order_project_id']])->find();
                $this->assign('project_order_info', $project_order_info);
            }
            $order_info = db('order')->where('order_id', '10')->find();
            if (empty($app_order_info)) {
                $this->error('操作失败');
            }
            $this->assign('invoice_info', $invoice_info);
            $this->assign('app_order_info', $app_order_info);
            $this->assign('order_info', $order_info);
            return $this->fetch('invoice_state');
        } else {
            $order_id = intval(input('param.app_order_id'));
            if ($order_id <= 0) {
                $this->error('操作失败');
            }
            $status = intval(input('param.status'));
            $invoice_state = intval(input('param.invoice_state'));

            $data['invoice_operation'] = Session::get('admin_id'); // 处理人
            $data['invoice_operation_name'] = Session::get('admin_name'); // 处理人
            $data['invoice_operation_time'] = time(); // 处理人
            if ($status == 1) {
                #成功
                $data['invoice_logistics'] = input('post.code', '');
                $data['invoice_status'] = '3';

            } else {
                $data['invoice_no_content'] = input('post.no_content');
                $data['invoice_status'] = '2';
            }

            $res = db('app_order')->where('app_order_id', $order_id)->data($data)->update();
            if (!$res) {
                dsLayerOpenSuccess('操作失败');
            } else {
                dsLayerOpenSuccess('操作成功');
            }

        }
    }

    #服务单审核发票
    public function service_invoice_state()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error('操作失败');
        }
        if (!request()->isPost()) {

            $tblname = 'invoice';
            $field = 'a.*,b.name,b.type,b.billing_type';
            $where['a.app_order_id'] = $order_id;
            $where['b.status'] = 1;
            $where['b.is_del'] = 0;
            $invoice_info = db($tblname . ' a')->join('__INVOICE_TYPE__ b', 'a.invoice_type_id=b.id')->where($where)->field($field)->find();
            //获取发票类型
            if (!empty($invoice_info['invoice_type_id'])) {
                $invoice_type_info = db('invoice_type')->where(['id' => $invoice_info['invoice_type_id']])->find();
                $this->assign('invoice_type_info', $invoice_type_info);
            }
            if (empty($invoice_info)) {
                $this->error('操作失败');
            }
            $s_order_info = db('s_order')->where('order_id', $order_id)->find();

            if (empty($s_order_info)) {
                $this->error('操作失败');
            }
            $this->assign('invoice_info', $invoice_info);
            $this->assign('s_order_info', $s_order_info);

            return $this->fetch('service_invoice_state');
        } else {
            $order_id = intval(input('param.service_s_order_id'));
            if ($order_id <= 0) {
                $this->error('操作失败');
            }
            $status = intval(input('param.status'));
            $invoice_state = intval(input('param.invoice_state'));

            // $data['invoice_operation']  = Session::get('admin_id'); // 处理人
            // $data['invoice_operation_name']  = Session::get('admin_name'); // 处理人
            // $data['invoice_operation_time']  = time(); // 处理人
            if ($status == 1) {
                #成功
                // $data['invoice_logistics']  = input('post.code','');
                $data['service_invoice_status'] = '3';

            } else {
                $data['service_invoice_reasons'] = input('post.no_content');
                $data['service_invoice_status'] = '2';
            }

            $res = db('s_order')->where('order_id', $order_id)->data($data)->update();
            if (!$res) {
                dsLayerOpenSuccess('操作失败');
            } else {
                dsLayerOpenSuccess('操作成功');
            }

        }
    }

    /**
     * 查看订单
     *
     */
    public function show_order()
    {
        $order_id = intval(input('param.order_id'));
        if ($order_id <= 0) {
            $this->error(lang('miss_order_number'));
        }
        $order_model = model('order');
        $order_info = $order_model->getOrderInfo(array('order_id' => $order_id), array('order_goods', 'order_common', 'store'));

        //订单变更日志
        $log_list = $order_model->getOrderlogList(array('order_id' => $order_info['order_id']));
        $this->assign('order_log', $log_list);

        //退货信息
        $refundreturn_model = model('refundreturn');
        $condition = array();
        $condition['order_id'] = $order_info['order_id'];
        $condition['refund_type'] = 2;
        $condition['seller_state'] = 2;
        $return_list = $refundreturn_model->getReturnList($condition);
        $this->assign('return_list', $return_list);

        //退款信息
        $new_condition = array();
        $new_condition['order_id'] = $order_info['order_id'];
        $refund_list = $refundreturn_model->getRefundDaList($new_condition);
        $this->assign('refund_list', $refund_list);

        //卖家发货信息
        if (!empty($order_info['extend_order_common']['daddress_id'])) {
            $daddress_info = model('daddress')->getAddressInfo(array('daddress_id' => $order_info['extend_order_common']['daddress_id']));
            $this->assign('daddress_info', $daddress_info);
        }

        #项目定制订单
        if ($order_info['app_order_type'] == 2) {
            $project_order_info = db('orderproject')->where(['order_id' => $order_info['app_order_project_id']])->find();
            $order_info['zhu_order_state'] = $project_order_info['order_state'];
        }

        #大订单退款
        if ($order_info['order_state'] == 20 && $order_info['refund_state'] == 1) {
            $order_info['order_state'] = '50';
        }


        $this->assign('order_info', $order_info);
        $this->assign('goods_status', array('0' => '正常', '1' => '退款待处理', '2' => '退货待处理', '3' => '换货待处理', '4' => '退货成功', '5' => '评价成功', '6' => '退款成功', '7' => '供应商处理换货成功', '8' => '运营商处理退货同意', '9' => '运营商处理换货同意'));
        $this->assign('order_status', ['0' => '已取消', '10' => '未付款', '20' => '已付款', '30' => '已发货', '40' => '已收货', '50' => '待退款']);
        $this->assign('project_order_status', ['0' => '待付款', '10' => '未付款', '20' => '已付款', '30' => '已发货', '40' => '已收货', '50' => '已取消', '60' => '已完成']);
        $this->assign('service_order_status', ['0' => '待付款', '10' => '未付款', '20' => '进行中', '30' => '已发货', '40' => '已收货', '50' => '已取消', '60' => '已完成']);
        return $this->fetch('show_order');
    }

    /**
     * 导出
     *
     */
    public function export_step1()
    {

        $order_model = model('order');
        $condition = array();
        $order_sn = input('param.order_sn');
        if ($order_sn) {
            $condition['order_sn'] = $order_sn;
        }
        $store_name = input('param.store_name');
        if ($store_name) {
            $condition['store_name'] = $store_name;
        }
        $order_state = input('param.order_state');
        if (in_array($order_state, array('0', '10', '20', '30', '40'))) {
            $condition['order_state'] = $order_state;
        }
        $payment_code = input('param.payment_code');
        if ($payment_code) {
            $condition['payment_code'] = $payment_code;
        }
        $buyer_name = input('param.buyer_name');
        if ($buyer_name) {
            $condition['buyer_name'] = $buyer_name;
        }
        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['add_time'] = array('between', array($start_unixtime, $end_unixtime));
        }

        if (!is_numeric(input('param.curpage'))) {
            $count = $order_model->getOrderCount($condition);
            $export_list = array();
            if ($count > self::EXPORT_SIZE) { //显示下载链接
                $page = ceil($count / self::EXPORT_SIZE);
                for ($i = 1; $i <= $page; $i++) {
                    $limit1 = ($i - 1) * self::EXPORT_SIZE + 1;
                    $limit2 = $i * self::EXPORT_SIZE > $count ? $count : $i * self::EXPORT_SIZE;
                    $export_list[$i] = $limit1 . ' ~ ' . $limit2;
                }
                $this->assign('export_list', $export_list);
                return $this->fetch('/public/excel');
            } else { //如果数量小，直接下载
                $data = $order_model->getOrderList($condition, '', '*', 'order_id desc', self::EXPORT_SIZE);
                $this->createExcel($data);
            }
        } else { //下载
            $limit1 = (input('param.curpage') - 1) * self::EXPORT_SIZE;
            $limit2 = self::EXPORT_SIZE;
            $data = $order_model->getOrderList($condition, '', '*', 'order_id desc', "{$limit1},{$limit2}");
            $this->createExcel($data);
        }
    }

    /**
     * 生成excel
     *
     * @param array $data
     */
    private function createExcel($data = array())
    {
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/export.lang.php');
        $excel_obj = new \excel\Excel();
        $excel_data = array();
        //设置样式
        $excel_obj->setStyle(array('id' => 's_title', 'Font' => array('FontName' => '宋体', 'Size' => '12', 'Bold' => '1')));
        //header
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_no'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_store'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_buyer'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_xtimd'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_count'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_yfei'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_paytype'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_state'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_storeid'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_buyerid'));
        $excel_data[0][] = array('styleid' => 's_title', 'data' => lang('exp_od_bemail'));
        //data
        foreach ((array)$data as $k => $v) {
            $tmp = array();
            $tmp[] = array('data' => 'DS' . $v['order_sn']);
            $tmp[] = array('data' => $v['store_name']);
            $tmp[] = array('data' => $v['buyer_name']);
            $tmp[] = array('data' => date('Y-m-d H:i:s', $v['add_time']));
            $tmp[] = array('format' => 'Number', 'data' => ds_price_format($v['order_amount']));
            $tmp[] = array('format' => 'Number', 'data' => ds_price_format($v['shipping_fee']));
            $tmp[] = array('data' => get_order_payment_name($v['payment_code']));
            $tmp[] = array('data' => get_order_state($v));
            $tmp[] = array('data' => $v['store_id']);
            $tmp[] = array('data' => $v['buyer_id']);
            $tmp[] = array('data' => $v['buyer_email']);
            $excel_data[] = $tmp;
        }
        $excel_data = $excel_obj->charset($excel_data, CHARSET);
        $excel_obj->addArray($excel_data);
        $excel_obj->addWorksheet($excel_obj->charset(lang('exp_od_order'), CHARSET));
        $excel_obj->generateXML($excel_obj->charset(lang('exp_od_order'), CHARSET) . input('param.curpage') . '-' . date('Y-m-d-H', time()));
    }


    /**
     * Notes:发票申请列表
     * User: shen
     * Date: 2020/5/13
     * Time: 16:52
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function invoice_manage()
    {
        $order_model = model('order');
        $condition = array();
        $keyword_type = array('order_sn', 'refund_sn', 'store_name', 'buyer_name', 'goods_name');
        $key = input('get.key');
        $type = input('get.type');
        if (trim($key) != '' && in_array($type, $keyword_type)) {
            $condition[$type] = array('like', '%' . $key . '%');
        }
        $order_sn = input('param.order_sn');
        if ($order_sn) {
            $condition['ds_app_order.order_sn'] = $order_sn;
        }
        $order_state = input('param.order_state');
        if (in_array($order_state, array('1', '2', '3'))) {
            $condition['invoice_type'] = $order_state;
        }

        $buyer_name = input('param.buyer_name');
        if ($buyer_name) {
            $condition['ds_app_order.member_name'] = $buyer_name;
        }
        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['ds_app_order.create_time'] = array('between', array($start_unixtime, $end_unixtime));
        }
        // $condition['ds_app_order.is_cancel'] = 0;
        if (isset($condition['ds_app_order.order_status']) && $condition['ds_app_order.order_status'] == 4) {
            $condition['ds_app_order.order_status'] = 1;
            $condition['ds_app_order.refund_price'] = 1;
        }
        $condition['app_order.invoice_status'] = 1;
        $order_list = $order_model->getInvoiceList($condition, 10);

        foreach ($order_list as $key => $value) {
            if ($value['app_order_type'] == 2) {
                $project_info = db('orderproject')->where(['order_id' => $value['app_order_project_id']])->find();
                $order_list[$key]['order_sns'] = $project_info['order_sn'];
            }
        }

        //p($refund_list);die;
        $this->assign('show_page', $order_model->page_info->render());
        $this->assign('refund_list', $order_list);
        $this->assign('type', $type);
        $this->assign('query_start_time', $query_start_time);
        $this->assign('query_end_time', $query_end_time);
        $this->setAdminCurItem('invoice_manage');
        return $this->fetch('invoice_manage');
    }


    /**
     * 获取卖家栏目列表,针对控制器下的栏目
     */
    protected function getAdminItemList()
    {
        $menu_array = array(
            array(
                'name' => 'index',
                'text' => '商城订单',
                'url' => url('Order/index')
            ),
            array(
                'name' => 'invoice_manage', 'text' => '发票申请', 'url' => url('Order/invoice_manage')
            ),
        );
        return $menu_array;
    }
}
